﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using sgsBase;

namespace TestApp.Account
{
    public partial class Forgot : SgsPage
    {
        protected override void PageLoad(object sender, EventArgs e)
        {
        }

		protected void EmailButton_Clicked(object sender, EventArgs e)
		{
			DbUsrUser uu = new DbUsrUser();
			uu.Email = txEmail.Text;
			uu.Status = 1;
			if (!uu.Select())
			{
				AddMessage("Email address provided was not found on file.");
				return;
			}
			Random r = new Random(DateTime.Now.Millisecond);

			DbUsrPasswordReset upr = new DbUsrPasswordReset();
			upr.UserId = uu.UserId;
			upr.SortBy = "dt_request desc";
			if (upr.Select())
			{
				if (upr.DtRequest.AddMinutes(5) > DateTime.Now)
				{
					AddMessage("You may not make multiple requests less than 5 minutes apart.");
					return;
				}
			}

			upr.HashCode = ApplicationHelper.CreateHashCode(20 + r.Next(10)); // this will make the hascode a random string between 21 and 30 characters
			upr.DtRequest = DateTime.Now;
			upr.IpAddress = Request.UserHostAddress;
			upr.Insert();

			string url = ApplicationHelper.AccountUrl + "PasswordReset.aspx?id=" + upr.HashCode;
			string body = "<h2>Password Reset</h2><p>You are receiving this email because you have forgotten your password on the " + ApplicationHelper.SiteTitle;
			body += " at " + ApplicationHelper.BaseUrl +". If you did not request this email...</p>";
			body += "<p> In order to reset your password, please follow the steps below:</p>";
			body += "<ol><li> Click the following link (or cut and paste it into your browser address bar) <a href='" + url + "'>" + url + "</a></li>";
			body += "<li>Enter a new password on the page provided</li><li>Enter the new password again</li><li>Press the 'Reset Password' button</li></ol>";
			body += "<p>Sincererly,<br>The Design Team</p>";

			string fullbody = Email.BuildWithTemplate(body); //, "..\\MailTemplate.htm");

			Email.Send(uu.Email, "Password Reset: " + ApplicationHelper.SiteTitle, fullbody);

			AddMessage("An email was sent to the provided email address with instructions on recovering your password.");
		}
    }
}
